package com.ihr360.shared.sequence.expression.function;

import com.ihr360.commons.lang.DateUtils;
import com.ihr360.expr.ExprDate;
import com.ihr360.expr.ExprException;
import com.ihr360.expr.ExprString;
import com.ihr360.expr.context.IEvaluationContext;
import com.ihr360.expr.core.AbstractFunction;
import com.ihr360.expr.core.Expr;
import com.ihr360.expr.utils.ExprUtils;

import java.util.Date;

public class DATETIME extends AbstractFunction {
    @Override
    public Expr evaluate(IEvaluationContext context, Expr[] args) throws ExprException {
        assertMinArgCount(args, 1);
        int argsLen = args.length;
        if (argsLen == 1) {//only have format
            Expr format = ExprUtils.evalArg(context, args[0]);
            String date = DateUtils.formatDateStr(new Date(), format.toString());
            return new ExprString(date);
        } else {
            Expr datetime = ExprUtils.evalArg(context, args[0]);
            Expr format = ExprUtils.evalArg(context, args[1]);
            if (datetime instanceof ExprDate) {
                String date = DateUtils.formatDateStr(((ExprDate) datetime).date, format.toString());
                return new ExprString(date);
            }
        }
        return new ExprString("");
    }
}